from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import QKeySequenceEdit
from PySide6.QtGui import QKeySequence, QKeyEvent
from qfluentwidgets import SettingCard, FluentIconBase, isDarkTheme, LineEdit, qconfig
from qfluentwidgets.common.style_sheet import FluentStyleSheet, themeColor

class CustomKeySequenceEdit(QKeySequenceEdit):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._is_recording = False

    def keyPressEvent(self, event: QKeyEvent):
        if not self._is_recording:
            self.clear()  # 清除之前的快捷键
            self._is_recording = True
        super().keyPressEvent(event)

    def keyReleaseEvent(self, event: QKeyEvent):
        super().keyReleaseEvent(event)
        if self._is_recording:
            self._is_recording = False
            # 确保只保留第一个快捷键组合
            if len(self.keySequence().toString().split(',')) > 1:
                first_sequence = self.keySequence().toString().split(',')[0]
                self.setKeySequence(QKeySequence(first_sequence))
            self.editingFinished.emit()
            self.clearFocus()  # 自动失去焦点

class ShortcutPickerSettingCard(SettingCard):
    """ 快捷键设置卡片 """
    
    shortcutChanged = Signal(str)

    def __init__(self, icon: FluentIconBase, title: str, content: str, 
                 configItem, parent=None):
        super().__init__(icon, title, content, parent)
        self.configItem = configItem
        
        # 创建快捷键输入框
        self.shortcutPicker = CustomKeySequenceEdit(self)
        self.shortcutPicker.setKeySequence(QKeySequence(self.configItem.value))
        self.shortcutPicker.setMinimumWidth(150)
        self.shortcutPicker.setFixedHeight(33)
        
        # 设置样式
        self._updateStyle()
        
        # 将快捷键输入框添加到右侧
        self.hBoxLayout.addWidget(self.shortcutPicker, 0, Qt.AlignRight)
        self.shortcutPicker.editingFinished.connect(self._onShortcutChanged)

    def _updateStyle(self):
        """ 更新样式 """
        if isDarkTheme():
            tc = "white"
            bc = "rgba(255, 255, 255, 0.0605)"
            bch = "rgba(255, 255, 255, 0.0837)"
            bg = "#202020"
            bgh = "#2b2b2b"
            bgf = "#2b2b2b"
        else:
            tc = "black"
            bc = "rgba(0, 0, 0, 0.0837)"
            bch = "rgba(0, 0, 0, 0.1581)"
            bg = "white"
            bgh = "#f5f5f5"
            bgf = "white"

        # 基础样式
        style = f'''
            QKeySequenceEdit {{
                color: {tc};
                background: {bg};
                border: 1px solid {bc};
                border-radius: 5px;
                padding: 5px 11px 5px 11px;
                font: 14px 'Segoe UI', 'Microsoft YaHei';
                selection-background-color: #009FAA;
            }}
            QKeySequenceEdit:hover {{
                background: {bgh};
                border: 1px solid {bch};
            }}
            QKeySequenceEdit:focus {{
                background: {bgf};
                border-bottom: 2px solid #009FAA;  /* 加粗下边框并设置颜色 */
                border-left: 1px solid {bc};
                border-right: 1px solid {bc};
                border-top: 1px solid {bc};
            }}
        '''

        self.shortcutPicker.setStyleSheet(style)

    def _onShortcutChanged(self):
        """ 快捷键改变时的处理 """
        shortcut = self.shortcutPicker.keySequence().toString()
        self.configItem.value = shortcut
        self.shortcutChanged.emit(shortcut)
        qconfig.save()  # 使用 qconfig 保存配置

    def getShortcut(self):
        """ 获取当前快捷键 """
        return self.shortcutPicker.keySequence().toString()

    def setShortcut(self, shortcut: str):
        """ 设置快捷键 """
        self.shortcutPicker.setKeySequence(QKeySequence(shortcut))